<?php

namespace app\admin\controller;

use app\model\TrademarkdynamicModel;
use think\App;
use think\exception\ValidateException;
use app\model\Article;
use app\model\ArticleCategory;
use think\View;

class TrademarkdynamicController extends Base
{
    public $model;
    public function __construct(TrademarkdynamicModel $model)
    {
        $this->model = $model;
    }
    function index()
	{
		$weid = weid();
		$keyword = input('post.keyword', '', 'serach_in');
		$query = $this->model->where(['weid' => $weid]);
		if (!empty($keyword)) {
			$query->where('title', 'like', '%' . $keyword . '%');
		}

		$res = $query->order('sort asc,id asc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {
			$vo['create_time'] = time_format($vo['create_time']);
			$vo['update_time'] = time_format($vo['update_time']);
		}

		$data['data'] = $res;
		return $this->json($data);
	}

	function listUpdate()
	{
		$data = only('id,status,sort');
		if (!$data['id']) throw new ValidateException('参数错误');
        $this->model->update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function update()
	{
		$id = input('id');
		$data = input('post.');
		$data['update_time'] = time();
		if(!empty($data['images'])){
		    $images = '';
		    foreach ($data['images'] as $k=>$v){
                $images .=','.$v['url'];
            }
            $data['images'] = trim($images,',');
        }

		if (empty($id)) {
			$data['weid'] = weid();
			$data['create_time'] = time();
			try {
				$res = $this->model->create($data);
				if ($res->id && empty($data['sort'])) {
                    $this->model->update(['sort' => $res->id, 'id' => $res->id]);
				}
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}

			return $this->json(['msg' => '添加成功', 'data' => $res->id]);
		} else {

			try {
                $this->model->update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}

	function getInfo()
	{
		$id =  input('id');
		if (!$id) throw new ValidateException('参数错误');
		$data = $this->model->find($id)->toArray();
        if(!empty($data['images'])){
            $goods_image = explode(',', $data['images']);
            $arr = [];
            foreach ($goods_image as $key => $vo) {
                $arr[$key]['url'] = $vo;
            }
            $data['images'] = $arr;
        }
		return $this->json(['data' => $data]);
	}

	function delete()
	{
		$idx =  input('id');
		if (!$idx) throw new ValidateException('参数错误');
        $this->model->destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}
}
